#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Jun 19 09:53:24 2020

@author: ua17
"""



from math import sin,radians,cos,asin,sqrt,acos,degrees,atan2



def get_distance(lon1, lat1, lon2, lat2):
    lon1, lat1, lon2, lat2 = map(radians, [lon1, lat1, lon2, lat2]) #radians 角度转弧度
    dlon = lon2 - lon1
    dlat = lat2 - lat1
    a = sin(dlat/2)**2 + cos(lat1) * cos(lat2) * sin(dlon/2)**2
    c = 2 * asin(sqrt(a)) # 反正弦
    return c * 6371

def _getDegree(ab,bc,ca):
    A = degrees(acos((ab * ab - bc * bc - ca * ca) / (-2 * bc * ca)))
    B = degrees(acos((bc * bc - ab * ab - ca * ca) / (-2 * ab * ca)))
    C = degrees(acos((ca * ca - ab * ab - bc * bc) / (-2 * ab * bc)))
    return [B,C,A]

def get_degrees(A = (0,0), B = (0,0), C = (0,0)):
    ab = get_distance(A[0],A[1], B[0],B[1])
    bc = get_distance(B[0],B[1], C[0],C[1])
    ca = get_distance(C[0],C[1], A[0],A[1])
    return _getDegree(ab, bc, ca) + [cos(radians(num)) for num in _getDegree(ab, bc, ca)]

def _get_az_angle(lon1, lat1, lon2, lat2):
    lon1, lat1, lon2, lat2 = map(radians, [lon1, lat1, lon2, lat2])
    dlon = lon2 - lon1
    y = sin(dlon) * cos(lat2)
    x = cos(lat1) * sin(lat2) - sin(lat1) * cos(lat2) * cos(dlon )
    brng = degrees(atan2(y,x))
    brng = (brng + 360) % 360
    return brng

def shadow(lon1, lat1, lon2, lat2):
    if (lon1 > 0 and lon2 > 0 ) or  (lon1 < 0 and lon2 < 0 ):
        dlon = lon2 - lon1
    else:
        dlon = abs(lon2) + abs(lon1)
        dlon = dlon if dlon < 180 else dlon - 360 #sign change when  dlon > 360
    dlat = lat2 - lat1
    
    distance = sqrt(dlon ** 2 + dlat **2 )
    x_shadow = dlon / distance
    y_shadow = dlat / distance
    return x_shadow, y_shadow
    

def compute_diff(lon, lat, ts,last_lon, last_lat, last_ts,):
    if last_ts == 0:
        return (0, 0, 3)
    if abs(lon - last_lon) >= 0.03 or abs(lat - last_lat) >= 0.03 or \
        (ts- last_ts).seconds >= 60:
        distance = get_distance(lon, lat, last_lon, last_lat)
        seconds = (ts- last_ts).seconds
        speed = (distance * 3600 / seconds) if seconds != 0 else 3
        return (distance, seconds, speed)
    return (-1, -1, 0)
